package com.yy.tech.inte.service.initializer;

import com.yy.tech.inte.context.AppContext;
import com.yy.tech.inte.context.Content;
import com.yy.tech.inte.service.wrapper.HttpRequestWrapper;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 设置HttpRequest的Authorization
 *
 * @author YY
 * @version 1.0.0
 * @date $ $
 * @description: TODO
 */
public interface RequestAuthorizer {
    /**
     * 是否支持该类型的HttpRequest的认证。
     * @param authType   认证类型
     * @param targetType  目标服务类型
     * @return  Default false。
     */
    default boolean support(String authType,String targetType){
        return false;
    }

    <T,S>void authorize(HttpRequestWrapper<T,S> wrapper);

    @Component
    @Order(Content.INT_ORDER_DEFAULT)
    public static class Impl implements RequestAuthorizer{

        @Override
        public boolean support(final String authType, final String targetType) {
            return Content.DEFAULT_AUTH_TYPE.equals(authType);
        }

        @Override
        public <T, S> void authorize(final HttpRequestWrapper<T, S> wrapper) {
            String authToken = wrapper.getAuthToken();
            if (StringUtils.isEmpty(authToken)){
                String authorization = AppContext.getAuthorization();
                if (!StringUtils.isEmpty(authorization)){
                    wrapper.addHeader(Content.APP_HEAD_AUTHORIZATION, authorization);
                }
            }else {
                wrapper.addHeader(Content.APP_HEAD_AUTHORIZATION,authToken);
            }
        }
    }
}
